package com.fastloan.mgt.invest.weixin.core;

import com.alibaba.fastjson.JSONObject;
import com.fastloan.mgt.invest.weixin.model.token.SaveToken;
import com.fastloan.mgt.invest.weixin.model.token.TokenModel;
import com.fastloan.utils.HttpUtil;
import com.kawins.spring.ContextProperty;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取access token,并存储在缓存中
 *
 * @author rankai
 */
@Service
public class AccessToken {

    private static Map<String, SaveToken> TOKEN_MAP = new HashMap<>();

    public static String getAccessToken() {
        //获取配置公众号相关配置数据信息
        String appId = (String) ContextProperty.getContextProperty("weixin.diaocha.app_id");
        String secret = (String) ContextProperty.getContextProperty("weixin.diaocha.appSecret");

        SaveToken saveToken = TOKEN_MAP.get(secret);
        if (saveToken != null && saveToken.getToken() != null && timeOut(saveToken.getCreate())) {
            System.out.println("token测试:" + saveToken);
            return saveToken.getToken();
        }

        //定义url
        String url = WeixinConstant.WEIXIN_TOKEN_API + appId + "&secret=" + secret;
        //调用获取access token
        String json = HttpUtil.get(url);
        System.out.println("JSON测试:" + json);
        TokenModel tokenModel;
        if (json != null) {
            tokenModel = JSONObject.parseObject(json, TokenModel.class);
            System.out.println("token测试:" + tokenModel);
        } else {
            System.out.println("access token 获取没有返回值");
            return "";
        }
        saveToken = new SaveToken();
        saveToken.setCreate(new Date().getTime());
        saveToken.setToken(tokenModel.getAccessToken());
        TOKEN_MAP.put(secret, saveToken);
        return tokenModel.getAccessToken();
    }

    private static boolean timeOut(long time) {
        long newTime = new Date().getTime();
        if (newTime - time > 7200 * 1000) {
            return false;
        }
        return true;
    }
}
